import axios from 'axios';
import store from './../store'
import { message } from 'ant-design-vue';
import { loginOut } from '../utils/expries'
import { prefix } from './env-setup'
import qs from 'qs';

// const baseURL = process.env.NODE_ENV === "dev" ? '/' : '/api'

let access_ = store.getters['getToken']
if (access_) {
  axios.defaults.headers['Authorization'] = access_
} else {
  axios.defaults.headers['Authorization'] = ''
}

axios.defaults.baseURL = prefix;
axios.defaults.timeout = 60000;

//响应拦截器
axios.interceptors.response.use(
  response => {
    if (response.data.code != 200) {
      message.destroy();
      message.warning(response.data.desc);
      if (response.data.code === -88) {
        loginOut()
      }
    }
    return response.data;
  },
  error => {
    let msg = '';
    let status = error && error.response && error.response.status;
    switch (status) {
      case 400:
        msg = '错误请求';
        break;
      case 401:
        msg = '未授权，请重新登录';
        break;
      case 403:
        msg = '拒绝访问';
        break;
      case 404:
        msg = '请求错误,未找到该资源';
        break;
      case 405:
        msg = '请求方法未允许';
        break;
      case 408:
        msg = '请求超时';
        break;
      case 500:
        msg = '服务器端出错';
        break;
      case 501:
        msg = '网络未实现';
        break;
      case 502:
        msg = '网络错误';
        break;
      case 503:
        msg = '服务不可用';
        break;
      case 504:
        msg = '网络超时';
        break;
      case 505:
        msg = 'http版本不支持该请求';
        break;
      default:
        msg = `连接错误${status || ''}`;
    }
    message.warning(msg);
    return Promise.resolve(error);
  }
);

export default {
  get(url, params) {
    return axios({
      method: 'GET',
      url,
      params,
    });
  },
  post(url, data) {
    return axios({
      method: 'POST',
      headers: {
        'content-type': 'application/json'
      },
      data,
      url,
    });
  },
  put(url, data) {
    return axios({
      method: 'PUT',
      headers: {
        'content-type': 'application/json'
      },
      data,
      url,
    });
  },
  delete(url, data) {
    return axios({
      method: 'DELETE',
      headers: {
        'content-type': 'application/json'
      },
      data,
      url,
    });
  },
  postLogin(url, data) {
    return axios({
      method: 'POST',
      headers: {
        'Authorization': ''
      },
      data: qs.stringify(data),
      url,
    });
  },
  postForms(url, data) {
    return axios({
      method: 'POST',
      headers: {
        'content-type': 'multipart/form-data'
      },
      data,
      url,
    });
  },
};